package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

import static sun.java2d.cmm.ColorTransform.In;

public class Client {
    private Socket socket;

    public Client(){
        try {
            System.out.println("正在连接服务器......");
            socket = new Socket("176.201.101.25",8088);
            System.out.println("与服务器建立连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() throws IOException {
        try {
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.setDaemon(true);
            t.start();

            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);

            Scanner scanner = new Scanner(System.in);
            while(true){
                String line = scanner.nextLine();
                if ("exit".equals(line)){
                    break;
                }
                pw.println("客户端："+line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client();
        client.start();
    }
    /**
     * 该线程任务负责读取服务端发送过来的消息
     * */
    private class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                //通过socket获取输入流，读取服务器发送过来的消息
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String line;
                while((line = br.readLine()) != null){
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
